package com.lagou.ipersistence.reflection.wrapper;

import com.lagou.ipersistence.reflection.MetaClass;
import com.lagou.ipersistence.reflection.MetaObject;
import com.lagou.ipersistence.reflection.ReflectionException;
import com.lagou.ipersistence.reflection.invoker.Invoker;
import com.lagou.ipersistence.reflection.property.PropertyTokenizer;

import java.lang.reflect.InvocationTargetException;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class BeanWrapper extends BaseWrapper {
    private final Object object;
    private final MetaClass metaClass;
    
    public BeanWrapper(MetaObject metaObject, Object object) {
        super(metaObject);
        this.object = object;
        this.metaClass = MetaClass.forClass(object.getClass(), metaObject.getReflectorFactory());
    }
    
    @Override
    public Object get(PropertyTokenizer prop) {
        Invoker invoker = metaClass.getGetInvoker(prop.getName());
        try {
           return invoker.invoke(object, null);
        } catch (Exception e) {
            throw new ReflectionException("无法对对象'" + metaObject + "'的属性'" + prop.getName() + "'设置参数. 原因: " + e, e);
        }
    }
    
    @Override
    public boolean hasSetter(String name) {
        return metaClass.hasGetter(name);
    }
    
    @Override
    public Class<?> getSetterType(String name) {
        return metaClass.getSetterType(name);
    }
    
    @Override
    public void set(PropertyTokenizer prop, Object value) {
        Invoker invoker = metaClass.getSetInvoker(prop.getName());
        Object[] params = {value};
        try {
            invoker.invoke(object, params);
        } catch (Exception e) {
            throw new ReflectionException("无法对对象'" + metaObject + "'的属性'" + prop.getName() + "'设置参数. 原因: " + e, e);
        }
    }
}
